/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-05-16 11:25:05
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-08-05 18:25:22
 * @FilePath: \dwys_web\extensions\phoenix-plugin-client\assets\core\net\bundle\bundle.ts
 * @Description: 
 */
import { UtilsArray } from "../../utils/Utils.Array";
import { Packet } from "../packet/packet";

export class Bundle {
    private _packets: Array<Packet>;
    private _data: Uint8Array | undefined;

    constructor() {
        this._packets = new Array<Packet>();
        this._data = undefined;
    }

    public getPackets(): Array<Packet> {
        return this._packets;
    }

    public finishData(verifyID:number):{vid:number, isClear:boolean}{
        let isClear = false;
        this._data = new Uint8Array(0);
        let sendList = new Array<number>();
        for (let i = 0; i < this._packets.length; i++) {
            verifyID++;
            let datas = this._packets[i].finishPacket(verifyID);
            if (this._data.length + datas.length > 1024){
                break;
            }
            this._data = UtilsArray.concatUint8Arrays(this._data, datas);
            if (i == this._packets.length - 1){
                isClear = true;
            }
            sendList.push(i);
        }
        // 遍历删除
        for (let i = 0; i < sendList.length; i++) {
            this._packets.splice(sendList[i], 1);
        }
        return { vid: verifyID, isClear: isClear};
    }    
    
    public getData(): Uint8Array {
        return this._data!;
    }

    public addPacket(packet: Packet) {
        this._packets.push(packet);
    }
}